<template>
	<view
		class="e-tabs"
		:class="{
			isFixed: isTabsFixed,
			'tabs-skelett': isSkelett
		}"
		:style="{
			top: getOffsetTop + 'px',
			backgroundColor: bgColor
		}"
	>
		<template v-if="isHideETabItem">
			<scroll-view scroll-x class="e-scroll-view" :scroll-left="scrollLeft" scroll-with-animation>
				<view
					class="e-scroll-box"
					:class="{
						'e-tabs-scorll-flex': !scroll,
						isMaterial: type === 'material'
					}"
				>
					<template>
						<slot name="left" :isFixed="isTabsFixed" />
					</template>

					<block v-for="(item, index) in tabsList" :key="index">
						<view :key="index" class="e-tab-item" @click="clickTab(index)" :class="{ active: current === index && !isSkelett }">
							<image
								v-if="isShowImage"
								lazy-load
								:class="{ isFixed: isTabsFixed }"
								:src="item[current === index ? 'activeIcon' : 'defaultIcon']"
							/>

							<text>{{ item[itemKey] || item || '' }}</text>
						</view>
					</block>

					<template v-if="isActiveIcon">
						<!-- tab 样式 -->
						<view class="e-tab-line" :style="[tabLineStyle]">
							<slot name="tabLine">
								<image class="tabs-default-status" src="@/static/icon/icon_sc_xian@3x.png" />
							</slot>
						</view>
					</template>
				</view>
			</scroll-view>
		</template>

		<template>
			<slot name="sort" :isFixed="isTabsFixed" />
		</template>
	</view>
</template>

<script>
import { getSystemInfo } from '@/utils';
import { getDomeInfo } from '@/utils/common';

export default {
	name: 'eTabs',

	props: {
		type: {
			type: String,
			default: 'frontPage'
		},

		isActiveIcon: {
			type: Boolean,
			default: true
		},

		scroll: {
			type: Boolean,
			default: true
		},

		list: {
			type: Array,
			default() {
				return [];
			}
		},

		itemKey: {
			type: String,
			default: 'label'
		},

		current: {
			type: [Number, String],
			default: 0
		},

		offsetTop: {
			type: Number,
			default: uni.upx2px(6)
		},

		duration: {
			type: [String, Number],
			default: 0.4
		},

		isSkelett: {
			type: Boolean,
			default: false
		},

		skelettSize: {
			type: Number,
			default: 6
		},

		isRgba: {
			type: Boolean,
			default: false
		},
		isShowImage:{
			type: Boolean,
			default: true
		}
	},

	data() {
		return {
			fixedTop: 0,
			scrollTop: 0,

			isFirst: false,
			itemsDomInfo: [],
			isTabsFixed: false
		};
	},

	watch: {
		list(n, o) {
			// list变动时，重制内部索引，否则可能导致超出数组边界的情况
			if (n.length !== o.length) this.currentIndex = 0;

			// 用$nextTick等待视图更新完毕后再计算tab的局部信息，否则可能因为tab还没生成就获取，就会有问题
			this.$nextTick(() => {
				this.init();
			});
		},

		isTabsFixed(status) {
			const { isFirst } = this;
			this.$emit('changeFixedCallBack', status);

			if (status && !isFirst) {
				this.$nextTick((e) => {
					this.init(status);

					this.$nextTick((e) => {
						this.isFirst = true;
					});
				});
			}
		}
	},

	computed: {
		bgColor() {
			const { isRgba, isTabsFixed } = this;

			if (isRgba) {
				return;
			}

			return `rgba(255, 255, 255, ${isTabsFixed ? 1 : 0})`;
		},

		getOffsetTop() {
			const { statusBarHeight, platform } = getSystemInfo();
			const mpHeight = statusBarHeight + (platform === 'ios' ? 44 : 48);

			return mpHeight;
		},

		tabLineStyle() {
			const { number, current, itemsDomInfo, duration } = this;
			const currentItemInfo = itemsDomInfo[current];

			const tabBarWidth = currentItemInfo?.width || 0;
			const tabBarPosition = currentItemInfo?.left || 0;

			const style = {
				width: `${tabBarWidth}px`,
				transform: `translate3d(${tabBarPosition}px, 0, 0)`,
				transition: `all ${number(duration) ? `${duration}s` : duration}`
			};

			return style;
		},

		scrollLeft() {
			const { itemsDomInfo, current } = this;
			if (current <= 1) return 0;

			const currentItem = itemsDomInfo[current];
			const frontItem = itemsDomInfo[current - 1];

			if (currentItem && frontItem) return currentItem.left - frontItem.width;

			return 0;
		},

		tabsList() {
			const { isSkelett, list, skelettSize } = this;

			if (!isSkelett) {
				return list;
			}

			return Array.from({ length: skelettSize }).map((item) => ({}));
		},

		isHideETabItem() {
			const { tabsList, isSkelett } = this;

			if (isSkelett || tabsList.length !== 1) {
				return true;
			}

			return false;
		}
	},

	mounted() {},

	methods: {
		// 验证十进制数字
		number(value) {
			return /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);
		},

		onSticky(status) {
			this.$emit('sticky', status);
		},

		// 初始化数据
		init(status) {
			const { isFirst, offsetTop, scrollTop, getOffsetTop } = this;

			!isFirst &&
				getDomeInfo.call(this, '.e-tab-item').then((res = []) => {
					if (res.length) {
						this.itemsDomInfo = res.map((e, i, arr) => {
							return {
								...e,
								left: e.left - arr[0].left
							};
						});

						this.tabBarWidth = res[0].width;
					}
				});

			!status &&
				getDomeInfo.call(this, '.e-tabs', false).then(({ top }) => {
					const fixedTop = top - getOffsetTop + offsetTop - scrollTop;
					console.log('🚀 ~ file: index.vue ~ line 260 ~ getDomeInfo.call ~ fixedTop', fixedTop);

					if (fixedTop <= 0) {
						return;
					}

					this.fixedTop = fixedTop;
				});
		},

		// 点击某一个tab菜单
		clickTab(index) {
			// 点击当前活动tab，不触发事件
			if (index === this.current) return;
			// 发送事件给父组件
			this.$emit('change', index);
		},

		changePageScroll(e) {
			const { scrollTop } = e;

			this.scrollTop = scrollTop;
			this.isTabsFixed = scrollTop >= this.fixedTop;
		}
	}
};
</script>

<style lang="scss" scoped>
@import '@/style/common.scss';

.e-tabs {
	&.isFixed {
		position: fixed;
		left: 0;
		right: 0;
		z-index: 999;
		padding-bottom: 20rpx;
		background: #f8f8f8;

		.e-scroll-box {
			padding-top: 32rpx;

			.e-tab-item {
				image {
					display: none;
				}

				text {
					font-size: 28rpx;
					// transform: scale(0.85) translateZ(0);
				}

				&.active {
					text {
						font-size: 32rpx;
						// transform: scale(1) translateZ(0);
					}
				}
			}

			&.isMaterial {
				padding-top: 24rpx;
				padding-bottom: 0;

				.e-tab-item {
					image {
						display: none;
					}

					text {
						font-size: 24rpx;
					}

					&.active {
						text {
							font-size: 24rpx;
						}
					}
				}
			}
		}

		.e-tab-line {
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	&.tabs-skelett {
		.e-tab-item {
			image {
				background: $skelettBgColor;
				border-radius: 50%;
				margin-top: 22rpx;
			}

			text {
				display: none;
			}
		}

		.isMaterial {
			.e-tab-item {
				min-width: 144rpx;
			}
		}
	}
}

::v-deep ::-webkit-scrollbar {
	display: none;
	width: 0 !important;
	height: 0 !important;
	-webkit-appearance: none;
	background: transparent;
}

.e-scroll-box {
	display: flex;
	position: relative;
	padding-bottom: 34rpx;

	&.e-tabs-scorll-flex {
		display: flex;
		justify-content: space-between;
	}

	&.isMaterial {
		padding-top: 24rpx;
		width: min-content;

		.e-tab-item {
			height: 56rpx;
			line-height: 56rpx;
			border-radius: 16rpx;
			background: #fff;

			margin-left: 16rpx;

			&:first-child {
				margin-left: 20rpx;
			}

			&:last-child {
				margin-right: 20rpx;
			}

			image {
				display: none;
			}

			text {
				color: #333;
				font-size: 24rpx;
				line-height: unset;
			}

			&.active {
				background: #ff6b11;

				text {
					color: #fff;
				}
			}
		}
	}
}

.e-scroll-view {
	width: 100%;
	white-space: nowrap;
	position: relative;
	margin-top: -6rpx;
}

.e-tab-item {
	display: flex;
	padding: 0 28rpx;
	align-items: center;
	flex-direction: column;
	transition-property: background-color, color; // 过渡效果

	text {
		color: #666;
		font-size: 24rpx;
		line-height: 34rpx;
		min-width: 96rpx;
		text-align: center;

		transition: transform 0.4s;
		transform: translateZ(0);
	}

	image {
		width: 92rpx;
		height: 92rpx;
		margin-bottom: 6rpx;
	}

	&.active {
		text {
			color: #333;
			font-weight: bold;
			transform: scale(1) translateZ(0);
		}
	}
}

.e-tab-line {
	position: absolute;
	bottom: 16rpx;
	left: 0;
	display: none;
}

// 修改样式
.tabs-default-status {
	width: 40rpx;
	height: 12rpx;
}
</style>
